package cn.endeavour.order.service.impl;


import cn.endeavour.basic.service.impl.BaseServiceImpl;
import cn.endeavour.basic.util.CodeGenerateUtils;
import cn.endeavour.basic.util.LoginContextUtil;
import cn.endeavour.basic.util.PageList;
import cn.endeavour.order.domain.AdoptOrder;
import cn.endeavour.order.domain.OrderAddress;
import cn.endeavour.order.domain.ProductOrder;
import cn.endeavour.order.domain.ProductOrderDetail;
import cn.endeavour.order.mapper.AdoptOrderMapper;
import cn.endeavour.order.mapper.OrderAddressMapper;
import cn.endeavour.order.mapper.ProductOrderDetailMapper;
import cn.endeavour.order.mapper.ProductOrderMapper;
import cn.endeavour.order.query.AdoptOrderQuery;
import cn.endeavour.order.query.ProductOrderQuery;
import cn.endeavour.order.service.IProductOrderService;
import cn.endeavour.org.domain.Employee;
import cn.endeavour.org.mapper.EmployeeMapper;
import cn.endeavour.org.mapper.ShopMapper;
import cn.endeavour.pay.constants.PayConstants;
import cn.endeavour.pay.domain.PayBill;
import cn.endeavour.pay.mapper.PayBillMapper;
import cn.endeavour.pay.service.IPayBillService;
import cn.endeavour.pet.domain.Pet;
import cn.endeavour.pet.mapper.PetMapper;
import cn.endeavour.product.domain.Product;
import cn.endeavour.product.mapper.ProductMapper;
import cn.endeavour.quartz.constants.JobConstants;
import cn.endeavour.quartz.domain.QuartzJobInfo;
import cn.endeavour.quartz.service.IQuartzService;
import cn.endeavour.user.domain.LoginInfo;
import cn.endeavour.user.domain.User;
import cn.endeavour.user.domain.UserAddress;
import cn.endeavour.user.mapper.UserAddressMapper;
import cn.endeavour.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class ProductOrderServiceImpl extends BaseServiceImpl<ProductOrder> implements IProductOrderService {

    @Autowired
    private ProductOrderMapper productOrderMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductOrderDetailMapper productOrderDetailMapper;

    @Autowired
    private PayBillMapper payBillMapper;

    @Autowired
    private IPayBillService payBillService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IQuartzService quartzService;

    @Override
    @Transactional
    public String productOrderSubmit(Map<String, Object> params, HttpServletRequest request) {
        // 获取地址id
        Long addressId = Long.parseLong(params.get("address_id").toString());
        // 取货方式
        Integer service_method = Integer.parseInt(params.get("service_method").toString());
        // 支付方式
        Long payType = Long.parseLong(params.get("pay_method").toString());
        // 宠物id
        Long productId = Long.parseLong(params.get("product_id").toString());
        // 订单数量
        Long orderCount = Long.parseLong(params.get("orderCount").toString());
        Long salePrice = Long.parseLong(params.get("salePrice").toString());
        // 通过id查询
        Product product = productMapper.loadById(productId);
        product.setSaleCount(product.getSaleCount() + orderCount);
        productMapper.update(product);
        // 获取登录人信息
        LoginInfo loginInfo = LoginContextUtil.getLoginInfo(request);
        // 通过loginInfo来查询用户信息
        User user = userMapper.loadByLoginInfoId(loginInfo.getId());
        // 创建订单
        // 将宠物信息和用户信息转换为领养订单
        ProductOrder productOrder = productUser2ProductOrder(product, salePrice, user);
        // 进行保存 返回自增主键
        productOrderMapper.save(productOrder);
        // 将此次订单服务进行保存转换为订单地址
        ProductOrderDetail productOrderDetail = initProductOrderDetail(product, productOrder.getId(), salePrice, orderCount);
        // 保存
        productOrderDetailMapper.save(productOrderDetail);
        // 支付
        // 生成支付订单
        PayBill payBill = initPayBill(user, productOrder, payType);
        payBillMapper.save(payBill);
        String payRequest = payBillService.payRequest(payBill);
        // 设置的定时器
        QuartzJobInfo info = new QuartzJobInfo();
        info.setTime(payBill.getLastPayTime());
        info.setType(JobConstants.OVER_TIME_NO_PAY_PRODUCT);
        info.setJobName(JobConstants.OVER_TIME_NO_PAY_PRODUCT + payBill.getUnionPaySn());
        HashMap<String, Object> map = new HashMap<>();
        map.put("productId", productOrder.getId());
        info.setParams(map);
        quartzService.addJob(info);
        return payRequest;
    }

    /**
     * 初始化支付订单
     *
     * @param user
     * @param productOrder
     * @param payType
     * @return
     */
    private PayBill initPayBill(User user, ProductOrder productOrder, Long payType) {
        PayBill payBill = new PayBill();
        payBill.setDigest(productOrder.getDigest());
        payBill.setMoney(productOrder.getPrice());
        payBill.setLastPayTime(new Date(System.currentTimeMillis() + PayConstants.ORDER_TIMEOUT));
        payBill.setPayChannel(payType);
        payBill.setUnionPaySn(productOrder.getPaySn());
        payBill.setBusinessType(PayConstants.BUSINESS_TYPE_PRODUCT);
        payBill.setBusinessKey(productOrder.getId());
        payBill.setUser_id(productOrder.getUser_id());
        payBill.setNickName(user.getUsername());
        payBill.setShop_id(productOrder.getShop_id());
        return payBill;
    }

    /**
     * @param product
     * @param id
     * @return
     */
    private ProductOrderDetail initProductOrderDetail(Product product, Long id, Long salePrice, Long orderCount) {
        ProductOrderDetail productOrderDetail = new ProductOrderDetail();
        BeanUtils.copyProperties(product, productOrderDetail);
        productOrderDetail.setSalePrice(new BigDecimal(salePrice));
        productOrderDetail.setSaleCount(orderCount);
        productOrderDetail.setOrder_id(id);
        productOrderDetail.setId(null);
        productOrderDetail.setProduct_id(product.getId());
        return productOrderDetail;
    }

    /**
     * 将服务转换为服务订单
     *
     * @param product 服务
     * @param user    登录用户
     * @return
     */
    private ProductOrder productUser2ProductOrder(Product product, Long salePrice, User user) {
        ProductOrder productOrder = new ProductOrder();
        // 进行赋值
        productOrder.setDigest("[摘要]对" + product.getName() + "服务订单！");
        productOrder.setPrice(new BigDecimal(salePrice));
        String orderSn = CodeGenerateUtils.generateOrderSn(product.getId());
        productOrder.setOrderSn(orderSn);
        String paySn = CodeGenerateUtils.generateUnionPaySn();
        productOrder.setPaySn(paySn);
        // 设置失效时间
        productOrder.setLastPayTime(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000));
        productOrder.setProduct_id(product.getId());
        productOrder.setUser_id(user.getId());
        productOrder.setShop_id(27L);
        return productOrder;
    }


    @Override
    public void cancelOrder(Long orderId) {
        // 查询服务订单
        ProductOrder productOrder = productOrderMapper.loadById(orderId);
        productOrder.setState(-1);
        productOrderMapper.update(productOrder);
        // 修改支付订单
        String paySn = productOrder.getPaySn();
        PayBill payBill = payBillMapper.loadByUnionPaySn(paySn);
        payBill.setState(-1);
        payBill.setUpdateTime(new Date());
        payBillMapper.update(payBill);

    }

    @Override
    public PageList<ProductOrder> queryAdminOrder(ProductOrderQuery productOrderQuery, HttpServletRequest request) {
        LoginInfo loginInfo = LoginContextUtil.getLoginInfo(request);
        // 查询shop_id
        Employee employee = employeeMapper.findByLoginInfoId(loginInfo.getId());
        productOrderQuery.setShop_id(employee.getShop_id());
        return super.queryPage(productOrderQuery);
    }

    @Override
    public PageList<ProductOrder> queryUserOrder(ProductOrderQuery productOrderQuery, HttpServletRequest request) {
        LoginInfo loginInfo = LoginContextUtil.getLoginInfo(request);
        // 查询shop_id
        User user = userMapper.loadByLoginInfoId(loginInfo.getId());
        productOrderQuery.setUser_id(user.getId());
        return super.queryPage(productOrderQuery);
    }


}
